package com.cgnpc.scp.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.manager.mybatis.entity.DataDict;
import com.cgnpc.scp.manager.mybatis.mapper.client.DataDictMapper;
import com.cgnpc.scp.manager.service.IDataDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DataDictServiceImpl implements IDataDictService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataDictServiceImpl.class);

    @Autowired
    private DataDictMapper dataDictMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public <T extends DataDict> AjaxResult saveOrUpdate(UserInfo loginUserInfo, Locale reqLocale, List<T> reqEntityList) {
        AjaxResult ajaxResult = null;

        try {
            Date nowDate = new Date();

            // begin 获取登录用户的信息
            String loginUserInfoUserId = loginUserInfo.getUserId();
            String loginUserInfoUserName = loginUserInfo.getUserName();
            // end 获取登录用户的信息

            for (DataDict reqDataDict : reqEntityList) {
                if (StringUtil.isNullOrSpace(reqDataDict.getId())) {
                    // 保存
                    DataDict usedDataDict = new DataDict();
                    usedDataDict.setId(IDHelper.uuidNew());
                    usedDataDict.setLang(reqDataDict.getLang());
                    usedDataDict.setDictGroupKey(reqDataDict.getDictGroupKey());
                    usedDataDict.setDictKey(reqDataDict.getDictKey());
                    usedDataDict.setDictText(reqDataDict.getDictText());
                    usedDataDict.setDictDesc(reqDataDict.getDictDesc());
                    usedDataDict.setCreateTime(nowDate);
                    usedDataDict.setCreateUser(loginUserInfoUserId);
                    usedDataDict.setCreateUserName(loginUserInfoUserName);
                    usedDataDict.setLastUpdateTime(nowDate);
                    usedDataDict.setLastUpdateUser(loginUserInfoUserId);
                    usedDataDict.setLastUpdateUserName(loginUserInfoUserName);
                    usedDataDict.setIsValid(reqDataDict.getIsValid());
                    usedDataDict.setSystemDataDict(reqDataDict.getSystemDataDict());
                    usedDataDict.setOrderIndex(reqDataDict.getOrderIndex());

                    int saveRows = dataDictMapper.insert(usedDataDict);
                } else {
                    // 修改
                    DataDict usedDataDict = new DataDict();
                    usedDataDict.setId(reqDataDict.getId());
                    usedDataDict.setLang(reqDataDict.getLang());
                    usedDataDict.setDictGroupKey(reqDataDict.getDictGroupKey());
                    usedDataDict.setDictKey(reqDataDict.getDictKey());
                    usedDataDict.setDictText(reqDataDict.getDictText());
                    usedDataDict.setDictDesc(reqDataDict.getDictDesc());
                    // usedDataDict.setCreateTime();
                    // usedDataDict.setCreateUser();
                    // usedDataDict.setCreateUserName();
                    usedDataDict.setLastUpdateTime(nowDate);
                    usedDataDict.setLastUpdateUser(loginUserInfoUserId);
                    usedDataDict.setLastUpdateUserName(loginUserInfoUserName);
                    usedDataDict.setIsValid(reqDataDict.getIsValid());
                    usedDataDict.setSystemDataDict(reqDataDict.getSystemDataDict());
                    usedDataDict.setOrderIndex(reqDataDict.getOrderIndex());

                    int updateRows = dataDictMapper.updateById(usedDataDict);
                }
            }

            ajaxResult = AjaxResult.success("全部保存或新增成功");
        } catch (Exception e) {
            LOGGER.error("save.error;", e);
            throw e;
        }

        return ajaxResult;
    }

    @Override
    public MyPageResult<DataDict> loadByPaging(DataDict reqEntity) {
        // begin 分页开始
        // 第几页
        int pageNum = reqEntity.getPageNum();
        // 每页的数量
        int pageSize = reqEntity.getPageSize();
        // 创建Page对象，将pageNum，pageSize参数传入，必须位于数据库查询数据的语句之前，否则不生效
//        Page<T> queryPage = PageHelper.startPage(pageNum, pageSize);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DataDict> page = new Page<>(pageNum, pageSize);
        // mybatis查询方式
//        DataDictExample queryExample = new DataDictExample();
//        DataDictExample.Criteria queryExampleCriteria = queryExample.createCriteria();

        QueryWrapper<DataDict> queryWrapper = new QueryWrapper<>();
        QueryWrapper<DataDict> order_index = queryWrapper.orderByAsc("order_index");


        // 设置查询条件
        // queryExampleCriteria.andCreateTimeIsNotNull();
        // 设置查询条件
        if (!StringUtil.isNullOrSpace(reqEntity.getLang())) {
            queryWrapper.eq("lang", reqEntity.getLang());
//            queryExampleCriteria.andProcessNameLike(SqlUtil.valueJoinLikeBoth(processInfo.getProcessName()));
        }
        // 组key
        if (!StringUtil.isNullOrSpace(reqEntity.getDictGroupKey())) {
            queryWrapper.eq("dict_group_key", reqEntity.getDictGroupKey());
        }
        IPage<DataDict> processInfoIPage = dataDictMapper.selectPage(page, order_index);
        // 执行查询
//        List<T> dbEntityList = (List<T>) dataDictMapper.selectByExample(queryExample);
        MyPageResult<DataDict> myPageResult = MyPageResultUtil.createMyPageResultPlus(processInfoIPage);
        return myPageResult;
    }

    @Override
    public List<DataDict> queryByDictGroupKey(DataDict reqEntity) {
        String reqDictGroupKey = reqEntity.getDictGroupKey();
        List<String> reqDictGroupKeyList = reqEntity.getDictGroupKeyList();

        List<String> usedDictGroupKeyList = new ArrayList<>();

        if (!StringUtil.isNullOrSpace(reqDictGroupKey)) {
            usedDictGroupKeyList.add(reqDictGroupKey.trim());
        }

        if (ListUtil.getListSizeWith0(reqDictGroupKeyList) > 0) {
            usedDictGroupKeyList.addAll(reqDictGroupKeyList);
        }

        QueryWrapper<DataDict> queryWrapper = new QueryWrapper<>();
        QueryWrapper<DataDict> order_index = queryWrapper.orderByAsc("order_index");

        queryWrapper.in("dict_group_key", usedDictGroupKeyList);

        return (List<DataDict>) dataDictMapper.selectList(order_index);
    }

    @Transactional
    @Override
    public <T extends DataDict> List<T> queryByDictGroupKey(List<String> reqDictGroupKeyList) {
        if (ListUtil.getListSizeWith0(reqDictGroupKeyList) <= 0) {
            return null;
        }

        QueryWrapper<DataDict> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByAsc("dict_group_key", "order_index");

        queryWrapper.in("dict_group_key", reqDictGroupKeyList);

        return (List<T>) dataDictMapper.selectList(queryWrapper);
    }

    @Transactional
    @Override
    public <T extends DataDict> List<T> queryByDictGroupKey(String reqDictGroupKey) {
        if (StringUtil.isNullOrSpace(reqDictGroupKey)) {
            return null;
        }

        return this.queryByDictGroupKey(Arrays.asList(reqDictGroupKey));
    }

}
